package com.service.Impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.omg.CORBA.Request;

import util.DB;

import com.service.UserService;
import com.vo.Uservo;

public class UserServiceImpl implements UserService {

	public void userAdd(DB db, Uservo vo) {
		String sql="insert into tb_users(userid,uname,pswd) values ('"+UUID.randomUUID().toString()+"','"+vo.getUname()+"','"+vo.getPswd()+"')";
		System.out.println("添加:"+sql);
		db.close();
	}
	/**
	 * 用户登录方法
	 * 返回值:
	 * 1:成功
	 * -1:密码错误
	 * -2:用户名不存在
	 */
	public int userLogin(DB db, Uservo vo) {
		int r=-1;
		String sql="select pswd from tb_users where uname='"+vo.getUname()+"'";
		System.out.println("登录"+sql);
		ResultSet rs=db.findDB(sql);
		try {
			if (rs.next()) {
				String s3=rs.getString("pswd");
				if (s3.equals(vo.getPswd())) {
					r=1;
				} else {
					r=-1;	
				}
			}else
			{
				r=-2;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return r;
	}
	/**
	 * 查询数据表中指定的用户名的记录的行数(注册时,限定用户名不能重复)
	 * @param 用户名
	 * @return 当前用户名在表中有几个
	 */
	public int userNameAsSame(DB db, String uname) {
		int r=-1;
		String sql="select count(uname) as gs from tb_users where uname='"+uname+"'";
		ResultSet rs=db.findDB(sql);
		try {
			if (rs.next()) {
				r=rs.getInt("gs");
			}
		} catch (SQLException e) {
		
			e.printStackTrace();
		}
		return r;
	}
	public Uservo userFindByUname(DB db, String uname) {
		Uservo vo=new Uservo();
		String sql="select userid,uname,pswd from tb_users where uname='"+uname+"'";
		ResultSet rs=db.findDB(sql);
		try {
			if (rs.next()) {
				vo.setUserid(rs.getString("userid"));
				vo.setUname(uname);
				vo.setPswd(rs.getString("pswd"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return vo;
	}
	public List<Uservo> userShowAll(DB db) {
		String sql="select userid,uname,pswd from tb_users";
		ResultSet rs=db.findDB(sql);
		List<Uservo> list=new ArrayList<Uservo>();
		try {
			while (rs.next()) {
				Uservo vo=new Uservo();
				vo.setUserid(""+rs.getInt("userid"));
				vo.setUname(rs.getString("uname"));
				vo.setPswd(rs.getString("pswd"));
				list.add(vo);
				vo=null;
			}
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}
		return list;
	}

}
